package com.sparrow.socket.udp;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;

/**
 * UDP 服务端
 */
public class UdpServer implements DisposableBean {

    private static final Logger logger = LoggerFactory.getLogger(UdpServer.class);

    private EventLoopGroup group;
    private Bootstrap bootstrap;
    private Channel channel;

    private ChannelInitializer<NioDatagramChannel> channelInitializer;

    public void start(int port) {
        group = new NioEventLoopGroup();
        bootstrap = new Bootstrap();
        try {
            bootstrap.group(group)
                    //设置udp channel
                    .channel(NioDatagramChannel.class)
                    .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    .option(ChannelOption.SO_BROADCAST, true) // 是否启用广播
                    .handler(new LoggingHandler(LogLevel.ERROR));

            if (channelInitializer != null) {
                bootstrap.handler(channelInitializer);
            }

            ChannelFuture future = bootstrap.bind(port).sync();
            this.channel = future.channel();
            logger.info("[{}] UDP server started on port {}", this.getClass().getSimpleName(), port);
            onBindSuc(future);
        } catch (Throwable e) {
            logger.error("UDP Server failed to start", e);
            System.exit(1);
        }
    }

    protected void onBindSuc(ChannelFuture channelFuture) {
        // 可以被子类覆盖
    }

    public void shutdown() {
        try {
            if (channel != null && channel.isOpen()) {
                channel.close().sync();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        try {
            if (group != null) {
                group.shutdownGracefully().sync();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        logger.info("Class:{} Server 关闭", this.getClass().getSimpleName());
    }

    public void setChannelInitializer(ChannelInitializer<NioDatagramChannel> channelInitializer) {
        this.channelInitializer = channelInitializer;
    }

    @Override
    public void destroy() throws Exception {
        shutdown();
    }
}
